﻿using System;
using System.Windows.Forms;
using System.Collections.Generic;

namespace TIFPDFCounter
{
	public partial class PageSizeManager : Form
	{
		public PageSizeManager()
		{
			InitializeComponent();
		}
		
		public PageSizeManager(List<Page> masterPageList)
		{
			InitializeComponent();
			if (masterPageList != null)
			{
				foreach (Page page in masterPageList)
				{
					dgvMasterPages.Rows.Add(page, page.Active, page.NameWithSize);
				}
			}
		}
		
		public List<Page> MasterPageListCopy { get; set; }
		
		void BtnNewClick(object sender, System.EventArgs e)
		{
			using (var pse = new PageSizeEditor())
			{
				pse.ShowDialog(this);
				if (pse.DialogResult == DialogResult.OK)
				{
					dgvMasterPages.Rows.Add(pse.PageObject, true, pse.PageObject.NameWithSize);
				}
			}
		}
		void BtnEditClick(object sender, System.EventArgs e)
		{
			if (dgvMasterPages.SelectedRows.Count == 0)
				return;
			var dgvr = dgvMasterPages.SelectedRows[0];
			Page page = dgvr.Cells["reference"].Value as Page;
			using (var pse = new PageSizeEditor(page))
			{
				pse.ShowDialog(this);
				if (pse.DialogResult == DialogResult.OK)
				{
					Page alteredPage = pse.PageObject;
					dgvr.Cells["reference"].Value = alteredPage;
					dgvr.Cells["name"].Value = alteredPage.NameWithSize;
				}
			}
		}
		void BtnDeleteClick(object sender, System.EventArgs e)
		{
			if (dgvMasterPages.SelectedRows.Count == 0)
				return;
			dgvMasterPages.Rows.Remove(dgvMasterPages.SelectedRows[0]);
		}
		void BtnOKClick(object sender, System.EventArgs e)
		{
			MasterPageListCopy = new List<Page>();
			foreach (DataGridViewRow dgvr in dgvMasterPages.Rows)
			{
				Page page = dgvr.Cells["reference"].Value as Page;
				page.Active = (bool)dgvr.Cells["active"].Value;
				MasterPageListCopy.Add(page);
			}
			DialogResult = DialogResult.OK;
			Close();
		}
		void BumpRow(DataGridViewRow dgvr, int indexOffset)
		{
			Page page = dgvr.Cells["reference"].Value as Page;
			int newIndex = dgvr.Index + indexOffset;
			dgvMasterPages.Rows.Remove(dgvr);
			newIndex = Math.Min(dgvMasterPages.RowCount, newIndex);
			newIndex = Math.Max(0, newIndex);
			dgvMasterPages.Rows.Insert(newIndex, page, page.Active, page.NameWithSize);
			dgvMasterPages.Rows[newIndex].Selected = true;
		}
		void BtnUpClick(object sender, System.EventArgs e)
		{
			if (dgvMasterPages.SelectedRows.Count == 0)
				return;
			BumpRow(dgvMasterPages.SelectedRows[0], -1);
		}
		void BtnDownClick(object sender, System.EventArgs e)
		{
			if (dgvMasterPages.SelectedRows.Count == 0)
				return;
			BumpRow(dgvMasterPages.SelectedRows[0], 1);
		}
	}
}
